﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace Structura.Silverlight.Infrastructure.Navigation
{
	public class IocNavigationContentLoader : INavigationContentLoader
	{
		public IocNavigationContentLoader(IPageProvider pageProvider)
		{
			_pageProvider = pageProvider;
		}
		private IPageProvider _pageProvider;

		private static PageResourceContentLoader DefaultPageContentLoader = new PageResourceContentLoader();

		public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState)
		{
			if (targetUri.ToString().Contains(".xaml"))
				return DefaultPageContentLoader.BeginLoad(targetUri, currentUri, userCallback, asyncState);

			var iar = new IocNavigationContentLoaderAsyncResult(asyncState);
			//Tries to load type from already loaded assemblies
			//iar.Result = App.Container.Resolve(GetComponentName(targetUri));
			iar.Result = _pageProvider.Resolve(GetComponentName(targetUri));
			userCallback(iar);
			return iar;
		}

		private string GetComponentName(Uri uri)
		{
			return uri.ToString().Split('?')[0];
		}

		public bool CanLoad(Uri targetUri, Uri currentUri)
		{
			if (targetUri.ToString().Contains(".xaml"))
				return DefaultPageContentLoader.CanLoad(targetUri, currentUri);
			// check if the IoC can resolve the object
			//return App.Container.Kernel.HasComponent(GetComponentName(targetUri));
			return _pageProvider.CanResolve(GetComponentName(targetUri));
		}

		public void CancelLoad(IAsyncResult asyncResult)
		{
			
		}

		public LoadResult EndLoad(IAsyncResult asyncResult)
		{
			if (asyncResult is IocNavigationContentLoaderAsyncResult)
				return new LoadResult((asyncResult as IocNavigationContentLoaderAsyncResult).Result);

			return DefaultPageContentLoader.EndLoad(asyncResult);
		}
	}
}
